//封装mysql
const mysql = require("mysql2");
let pools: { [key: string]: any } = {}; //连接池
let db = (sql: string, host = "127.0.0.1") => {
  if (!pools.hasOwnProperty(host)) {
    //是否存在连接池
    pools[host] = mysql.createPool({
      //不存在创建
      host: host,
      port: "3306",
      user: "root",
      password: "root",
      database: "sdsn_koa",
    });
  }
  return new Promise((resolve, reject) => {
    pools[host].getConnection((err: string, connection: any) => {
      //初始化连接池
      if (err) {
        console.log(err, "数据库连接失败");
        reject(err);
      } else
        connection.query(sql, (err: string, results: any) => {
          // console.log("sql语句：", sql);

          //去数据库查询数据
          connection.release(); //释放连接资源
          if (err) {
            console.error(err, sql);

            reject(err);
          } else resolve(results);
        });
    });
  });
};

module.exports = db;
